import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import constantRoutes from '../constant/constantRoutes'
import userApi from '../api/user.js';

import filePreview from '../views/filePreview/filePreview.vue'

Vue.use(Router)

const whiteList = ['/login', "/apply", "/applyForm", "/bbs",
    "/bbsUser/login", "/bbs/bbsindex", "/bbs/bbswrite", "/filePreview/filePreview",
]

const router = new Router({
    mode: "hash",
    routes: [...constantRoutes,]
})
//从后台动态加载前端路由的时候使用
// router.$addRoutes = function (params) {
//     //router使用matcher来匹配前端路由，如果使用新建的matcher，就相当于清空了之前添加的路由
//     router.matcher = new Router().matcher;
//     //重新添加路由
//     router.addRoutes(params)
// }

// router.beforeEach((to, from, next) => {
//     if (store.state.user) {
//         if (store.state.menus.length == 0) {
//             store.dispatch("GENERATE_ROUTES").then(() => {
//                 next()
//             })
//         } else {
//             next()
//         }
//     } else {
//         next()
//     }
// })

// 从后台动态加载前端路由的时候使用
// export restRoute  (params) {
//     //router使用matcher来匹配前端路由，如果使用新建的matcher，就相当于清空了之前添加的路由
//     router.matcher = new Router().matcher;
//     //重新添加路由
//     router.addRoutes(params)
// }


//使用钩子函数判断路由是否需要拦截（钩子函数在路由前进行判断
router.beforeEach(async (to, from, next) => {
    if (to.query.token){
		store.commit("SET_TOKEN", to.query.token);
		// 获取用户信息
		let user = JSON.parse(to.query.user);
		userApi.getUser({id:user.id}).then(res =>{
			if (res.code === 200){
				let loginUser = res.data
				store.commit("SET_USER", loginUser);
				localStorage.setItem("userInfo",JSON.stringify(loginUser));
				localStorage.setItem("role", loginUser.roleId);
			}
		}).catch(err =>{
			store.commit("SET_USER", user);
			localStorage.setItem("userInfo",to.query.user);
			localStorage.setItem("role", user.roleId);
		})
        import("../assets/css/webview.css")
	}

    const hasToken = store.getters.token
    console.log("hastoken", hasToken)

    if (hasToken) {
        console.log("【鉴权】有token信息")
        if (to.path === '/login') {
            next({
                path: '/index'
            })
            // console.log("已登录，无需前往登录页面")
        } else {
            const hasUser = store.getters.user && store.getters.menus.length > 0
            if (hasUser) {
                console.log("【跳转】有用户信息和菜单信息")
                next()
            } else {
                try {
                    const accessRoutes = await store.dispatch('GENERATE_ROUTES')

                    router.addRoutes(accessRoutes)

                    next({
                        ...to,
                        replace: true
                    })
                } catch (error) {
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }



    // if (to.path == '/' || to.path == '/login') {
    //     next()
    // }
    // 跳转页面的同时加载菜单
    // if (store.state.user && store.state.menus.length == 0) {
    //     initMenu(router, store)
    //     next()
    //     // store.dispatch("GENERATE_ROUTES").then(() => {
    //     //     next()
    //     // })
    // } else {
    //     next()
    // }
})


// 初始化菜单
// const initMenu = (router, store) => {
//     axios.get('/sysMenu/menuRoute').then(resp => {

//         if (resp.status) {
//             // var indexRoutes = formatRoutes(resp.data)
//             // for (let i in constantRoutes) {
//             //     if (constantRoutes[i].path === "/home") {
//             //         constantRoutes[i].children = indexRoutes
//             //     }
//             // }
//             store.commit('SET_MENU', menuRoutes)
//         }
//     })

// }

import { menu } from "../common/menu"

// 数据处理
const formatRoutes = (routes) => {

    let fmtRoutes = []
    routes.forEach(route => {
        if (route.children) {
            route.children = formatRoutes(route.children)
        }
        var str = route.component.length > 0 ? route.component : "/Home"
        // 动态加载路由
        let fmtRoute = {
            path: route.path,
            component: (resolve) => require(['../views' + str + '.vue'], resolve),
            name: route.name,
            title: route.title,
            icon: route.icon,
            hidden: route.hidden,
            children: route.children
        }
        fmtRoutes.push(fmtRoute)
    })
    return fmtRoutes
}

// var menuRoutes = formatRoutes(menu.children)
// router.addRoutes(menuRoutes)

router.addRoute({
    path: '/filePreview/filePreview',
    component: filePreview,
})




export default router